<?php
namespace app\admin\controller;
use app\AdminBaseController;
use think\facade\Request;
use think\facade\Filesystem;
use think\facade\Db;
use app\admin\model\MediaModel;

class Video extends AdminBaseController {

    public function index() {
        $where = array();
        $where[] = array('type','=',2);
        if(isset($_GET['title'])&&!empty($_GET['title'])) {
            $name = $_GET['title'];
            $where[] = array('title','like',"%$name%");
        }
        $page = isset($_GET['page'])?$_GET['page']:1;
        $pageSize = isset($_GET['pageSize'])?$_GET['pageSize']:10;
        $count = MediaModel::where($where)->count('id');
        $list = MediaModel::field('*')->where($where)->order('addtime desc')->page($page,$pageSize)->select();
        foreach($list as $value) {
            $value['addtime'] = date('Y-m-d H:m:s',$value['addtime']);
        }
        return array(
            'count'=>$count,
            'list'=>$list
        );
    }

    public function add() {
        $file = Request::file('file');
        $videoFile = Request::file('video');
        $coverPath;
        if($file) {
            $result = $this->uploadImg($file);
            if($result&&!$result['success']) {
                echo json_encode($result);
                die();
            }
            $coverPath = $result['path'];
        }
        
        $data = array(
            'title'=>$_POST['name'],
            'addtime'=>time(),
            'updatetime'=>time(),
            'type'=>2,
            'source'=>$_POST['source']
        );

        if($_POST['source']=='1') {
            $path;
            if($videoFile) {
                $result2 = $this->uploadVideo($videoFile);
                if($result2&&!$result2['success']) {
                    echo json_encode($result2);
                    die();
                }
                $path = $result2['path'];
            }
            if(isset($path)) {
                $data['path'] = $path;
            }
        } else {
            $data['path'] = $_POST['url'];
        }
        
        
        
        if(isset($_POST['desc'])&&!empty($_POST['desc'])) {
            $data['desc'] = $_POST['desc'];
        }
        if(isset($coverPath)) {
            $data['thumb'] = $coverPath;
        }

        
        $res = MediaModel::insert($data);
        if($res) {
            echo json_encode(array('success'=>true,'message'=>'添加成功！'));
        } else {
            echo json_encode(array('success'=>false,'message'=>'添加失败！'));
        }
    }


    public function edit() {
        $id = $_POST['id'];
        $videoItem = MediaModel::where('id',$id)->find();
        $file = Request::file('file');
        $videoFile = Request::file('video');
        $coverPath;
        if($file) {
            $result = $this->uploadImg($file);
            if($result&&!$result['success']) {
                echo json_encode($result);
                die();
            }
            $coverPath = $result['path'];
            if(isset($videoItem['thumb'])) {
                if(file_exists(public_path().'storage/'.$videoItem['thumb'])) {
                    unlink(public_path().'storage/'.$videoItem['thumb']);
                }
            }            
        }
        
        $data = array(
            'title'=>$_POST['name'],
            'addtime'=>time(),
            'updatetime'=>time(),
            'type'=>2,
            'source'=>$_POST['source']
        );

        if($_POST['source']=='1') {
            $path;
            if($videoFile) {
                $result2 = $this->uploadVideo($videoFile);
                if($result2&&!$result2['success']) {
                    echo json_encode($result2);
                    die();
                }
                $path = $result2['path'];  
                $path2 = public_path().'storage/'.$path;              
                unset($path2);
                if($videoItem['source']==1) {
                    $propath = public_path().'storage/'.$videoItem['path'];
                    if(file_exists($propath)) {
                        try{
                            unset($propath);
                            unlink($propath);
                        } catch (\Exception $e) {
                            // print_r(array('success'=>false,'message'=>$e->getMessage()));
                            // die;
                        }
                    }
                }
            }
            if(isset($path)) {
                $data['path'] = $path;
            }
        } else {
            $data['path'] = $_POST['url'];
            if($videoItem['source']==1) {
                $propath2 = public_path().'storage/'.$videoItem['path'];
                if(file_exists($propath2)) {
                    try{
                        unset($propath2);
                        unlink($propath2);
                    } catch (\Exception $e) {
                        
                    }
                }
            }
        }
        
        if(isset($_POST['desc'])&&!empty($_POST['desc'])) {
            $data['desc'] = $_POST['desc'];
        }
        if(isset($coverPath)) {
            $data['thumb'] = $coverPath;
        }
        
        $res = MediaModel::where('id',$id)->update($data);
        if($res) {
            echo json_encode(array('success'=>true,'message'=>'编辑成功！'));
        } else {
            echo json_encode(array('success'=>false,'message'=>'编辑失败！'));
        }
    }

    public function del() {
        $id = $_GET['id'];
        $videoItem = MediaModel::where('id',$id)->find();
        if(isset($videoItem['thumb'])) {
            if(file_exists(public_path().'storage/'.$videoItem['thumb'])) {
                unlink(public_path().'storage/'.$videoItem['thumb']);
            }
        }
        if($videoItem['source']==1) {
            $propath2 = public_path().'storage/'.$videoItem['path'];
            if(file_exists($propath2)) {
                try{
                    unset($propath2);
                    unlink($propath2);
                } catch (\Exception $e) {
                    
                }
            }
        }
        $result = MediaModel::where('id',$id)->delete();
        if($result) {
            echo json_encode(array('success'=>true,'message'=>'编辑成功！'));
        } else {
            echo json_encode(array('success'=>false,'message'=>'编辑失败！'));
        }
    }

    protected function uploadVideo($file) {
        $result;
        try{
            $saveName = Filesystem::disk('public')->putFile( 'video', $file, 'data');
            $result = array('success'=>true,'path'=>$saveName);
        } catch (\Exception $e) {
            $result = array('success'=>false,'message'=>$e->getMessage());
        }
        return $result;
    }

    protected function uploadImg($file) {
        $result;
        try{
            validate(['imgFile'=>[
                'fileSize' => 410241024,
                'fileExt' => 'jpg,jpeg,png,bmp,gif',
                'fileMime' => 'image/jpeg,image/png,image/gif',
            ]])->check(['file' => $file]);
            $saveName = Filesystem::disk('public')->putFile( 'videocover', $file, 'data');
            $result = array('success'=>true,'path'=>$saveName);
        } catch (\Exception $e) {
            $result = array('success'=>false,'message'=>$e->getMessage());
        }
        return $result;
    }
}